/*
 * Copyright (c) 2009 the original author or authors
 * 
 * Permission is hereby granted to use, modify, and distribute this file 
 * in accordance with the terms of the license agreement accompanying it.
 */

package org.robotlegs.mvcs
{
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	import org.robotlegs.base.EventMap;
	import org.robotlegs.base.MediatorBase;
	import org.robotlegs.core.IEventMap;
	import org.robotlegs.core.IMediatorMap;
	

public class Mediator extends MediatorBase
{
	
	[Inject]
	public var contextView:DisplayObjectContainer;
	
	[Inject]
	public var mediatorMap:IMediatorMap;

	protected var _eventDispatcher:IEventDispatcher;

	protected var _eventMap:IEventMap;
	

	
	override public function preRemove():void
	{
		if (_eventMap)
			_eventMap.unmapListeners();
		super.preRemove();
	}
	
	
	public function get eventDispatcher():IEventDispatcher{return _eventDispatcher;}
	
	[Inject]
	public function set eventDispatcher(value:IEventDispatcher):void
	{
		_eventDispatcher = value;
	}
	

	protected function get eventMap():IEventMap
	{
		return _eventMap || (_eventMap = new EventMap(eventDispatcher));
	}
	

	protected function dispatch(event:Event):Boolean
	{
		if(eventDispatcher.hasEventListener(event.type))
			return eventDispatcher.dispatchEvent(event);
		return false;
	}
	

	protected function addViewListener(type:String, listener:Function, eventClass:Class = null, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = true):void
	{
		eventMap.mapListener(IEventDispatcher(viewComponent), type, listener, 
			eventClass, useCapture, priority, useWeakReference); 
	}


	protected function removeViewListener(type:String, listener:Function, eventClass:Class = null, useCapture:Boolean = false):void
	{
		eventMap.unmapListener(IEventDispatcher(viewComponent), type, listener,
			eventClass, useCapture);
	}


	protected function addContextListener(type:String, listener:Function, eventClass:Class = null, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = true):void
	{
		eventMap.mapListener(eventDispatcher, type, listener, 
			eventClass, useCapture, priority, useWeakReference); 									   
	}


	protected function removeContextListener(type:String, listener:Function, eventClass:Class = null, useCapture:Boolean = false):void
	{
		eventMap.unmapListener(eventDispatcher, type, listener,
			eventClass, useCapture);
	}
}
}
